<template>
  <div class="h-100" data-flex="main:center cross:center">
    <el-card class="login">
      <template v-slot:header>
        <span class="f-16 f-b">登录</span>
      </template>
      <form-create v-model="fApi" :rule="rule" :option="option" class="inline-btn"></form-create>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'OsLogin',
  data () {
    return {
      captcha: {},
      fApi: {},
      rule: [
        {
          type: 'el-input',
          title: '用户名',
          field: 'username',
          validate: [{ type: 'string', required: true, message: '请输入用户名' }]
        },
        {
          type: 'el-input',
          title: '密码',
          field: 'password',
          props: { type: 'password' },
          validate: [{ type: 'string', required: true, message: '请输入密码' }]
        },
        {
          type: 'os-captcha',
          title: '验证码',
          field: 'captcha',
          validate: [
            { type: 'string', len: 4, required: true, message: '请输入4位验证码' }
          ],
          on: {
            change: val => (this.captcha = val)
          }
        }
      ],
      option: {
        global: {
          '*': {
            props: {
              size: 'medium',
              clearable: true
            }
          }
        },
        form: {},
        submitBtn: {
          icon: 'el-icon-user',
          innerText: '登录',
          nativeType: 'submit'
        },
        onSubmit: this.onSubmit
      }
    }
  },
  methods: {
    async onSubmit () {
      const formData = this.fApi.formData()
      this.fApi.btn.loading(true)
      formData.captchaCode = this.captcha.code
      const { data } = await this.$store.dispatch(this.$config?.actions?.login || 'login', formData)
      this.fApi.btn.loading(false)
      if (data) {
        localStorage.setItem('token', data.token)
        this.$router.push('/')
        this.$utils.message.success('登录成功')
      } else {
        this.captcha.refresh()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .login{
    width: 500px;
  }
</style>
